layui.use(['table', 'admin', 'ax'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;

    /**
     * 管理
     */
    var LxSpYsy = {
        tableId: "lxSpYsyTable"
    };

    /**
     * 初始化表格的列
     */
    LxSpYsy.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'spId', hide: true, title: '条形码'},
            {field: 'spName', sort: true, title: '名称'},
            {field: 'spGuige', sort: true, title: '规格'},
            {field: 'spDanwei', sort: true, title: '单位'},
            {field: 'spCd', sort: true, title: '产地'},
            {field: 'spChl', sort: true, title: '存货量'},
            {field: 'spLb', sort: true, title: '所属类别'},
            {field: 'spLsj', sort: true, title: '零售价'},
            {field: 'spPfj', sort: true, title: '批发价'},
            {field: 'spBz', sort: true, title: '备注'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    LxSpYsy.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        table.reload(LxSpYsy.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
                 // 搜索按钮点击事件
                 $('#btnSearch').click(function () {
                     LxSpYsy.search();
                 });
                 // 添加按钮点击事件
                 $('#btnAdd').click(function () {
                     LxSpYsy.openAddDlg();
                 });
                 // 导出excel
                 $('#btnExp').click(function () {
                     LxSpYsy.exportExcel();
                 });
                 $('#btnBuy').click(function () {
                     LxSpYsy.buy();
                 });
            }
        });
    };

    LxSpYsy.buy = function () {
        let checkStatus = table.checkStatus(LxSpYsy.tableId);
        if (checkStatus.data.length === 0) {
            Feng.error("请选择要购买的商品");
        } else {
            layer.prompt({title: '请输入购买数量', fromType: 0}, function (value, index) {
                let buyQuantity = parseInt(value);
                let selectData = checkStatus.data;
                let spChl = parseInt(selectData[0].spChl)
                if (buyQuantity > spChl) {
                    Feng.error("购买数量超过库存数量");
                } else {
                    layer.confirm('是否购买' + buyQuantity + '商品？', {
                            btn: ['确定', '取消']
                        }, function (index) {
                            layer.msg('购买实现', {icon: 1});
                            layer.close(index);
                            console.log(buyQuantity);
                            console.log(selectData[0].spId);
                            // 构造订单数据
                            spChl = spChl - buyQuantity;
                            selectData[0].spChl = spChl;
                            table.reload(LxSpYsy.tableId, {
                                data: selectData
                            });
                            console.log(spChl);
                            console.log(selectData[0].spChl);
                            layer.open({
                                type: 1,
                                title: '订单购买成功',
                                area: ['500px', '300px'],
                                content: '<div style="padding: 20px;">'
                                    + '订单号:' + selectData[0].spChl
                                    + '<br>商品名称:' + selectData[0].spName
                                    + '<br>购买数量:' + buyQuantity
                                    + '<br>总价:' + buyQuantity * selectData[0].spLsj
                                    + '<br>购买时间:' + new Date()
                                    + '<br>剩余库存:' + spChl
                                    + '</div>'
                            });
                            // 发送异步请求生成订单并减少库存
                            var ajax = new $ax(Feng.ctxPath + "/lxSpYsy/update?spName="+selectData[0].spName+"&spChl="+spChl, function (data) {
                                Feng.success("购买成功!");
                                table.reload(LxSpYsy.tableId);
                            }, function (data) {
                                Feng.error("购买失败!" + data.responseJSON.message + "!");
                            });

                            ajax.start();
                        }
                    );

                }
            })
        }
    }
            ;
            /**
             * 弹出添加对话框
             */
            LxSpYsy.openAddDlg = function () {
                window.location.href = Feng.ctxPath + '/lxSpYsy/add';
            };

            /**
             * 导出excel按钮
             */
            LxSpYsy.exportExcel = function () {
                var checkRows = table.checkStatus(LxSpYsy.tableId);
                if (checkRows.data.length === 0) {
                    Feng.error("请选择要导出的数据");
                } else {
                    table.exportFile(tableResult.config.id, checkRows.data, 'xls');
                }
            };
            /**
             * 点击编辑
             *
             * @param data 点击按钮时候的行数据
             */
            LxSpYsy.openEditDlg = function (data) {
                window.location.href = Feng.ctxPath + '/lxSpYsy/edit?spId=' + data.spId;
            };

            /**
             * 点击删除
             *
             * @param data 点击按钮时候的行数据
             */
            LxSpYsy.onDeleteItem = function (data) {
                var operation = function () {
                    var ajax = new $ax(Feng.ctxPath + "/lxSpYsy/delete", function (data) {
                        Feng.success("删除成功!");
                        table.reload(LxSpYsy.tableId);
                    }, function (data) {
                        Feng.error("删除失败!" + data.responseJSON.message + "!");
                    });
                    ajax.set("spId", data.spId);
                    ajax.start();
                };
                Feng.confirm("是否删除?", operation);
            };

            // 渲染表格
            var tableResult = table.render({
                elem: '#' + LxSpYsy.tableId,
                url: Feng.ctxPath + '/lxSpYsy/list',
                page: true,
                limit: 20,
                height: "full-60",
                toolbar: '#toolbarfrom',
                cellMinWidth: 100,
                cols: LxSpYsy.initColumn()
            });

            // 搜索按钮点击事件
            $('#btnSearch').click(function () {
                LxSpYsy.search();
            });

            // 添加按钮点击事件
            $('#btnAdd').click(function () {
                LxSpYsy.openAddDlg();
            });

            // 导出excel
            $('#btnExp').click(function () {
                LxSpYsy.exportExcel();
            });
            $('#btnBuy').click(function () {
                LxSpYsy.buy();
            });

            // 工具条点击事件
            table.on('tool(' + LxSpYsy.tableId + ')', function (obj) {
                var data = obj.data;
                var layEvent = obj.event;
                if (layEvent === 'edit') {
                    LxSpYsy.openEditDlg(data);
                } else if (layEvent === 'delete') {
                    LxSpYsy.onDeleteItem(data);
                }
            });


  });